package org.lemon.springmysqltest.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.lemon.springmysqltest.entity.Order;
import org.lemon.springmysqltest.repository.OrderRepository;
import org.lemon.springmysqltest.service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * @author : Lemon
 * @date : 2025-05-21 22:17
 **/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    private final OrderRepository orderRepository;

    public OrderServiceImpl(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    @Override
    public Order createOrder(Order order) {
        return orderRepository.save(order);
    }

    @Override
    public Optional<Order> getOrderById(Long id) {
        return orderRepository.findById(id);
    }

    @Override
    public List<Order> getAllOrders() {
        return orderRepository.findAll();
    }

    @Override
    public Order updateOrder(Long id, Order order) {
        if (!orderRepository.existsById(id)) {
            throw new RuntimeException("订单不存在");
        }
        order.setId(id);
        return orderRepository.save(order);
    }

    @Override
    public void deleteOrder(Long id) {
        orderRepository.deleteById(id);
    }

    @Override
    @Transactional
    public Order adjustOrderA() throws InterruptedException {

        // 查询id=1的订单
        Order order = orderRepository.findById(1L)
                .orElseThrow(() -> new RuntimeException("订单不存在"));

        // 休眠5秒
        Thread.sleep(5000);

        // 金额-100
        order.setAmount(order.getAmount().subtract(BigDecimal.valueOf(100)));

        // 更新时间
        order.setTradeTime(LocalDateTime.now());

        // 保存
        return orderRepository.save(order);
    }

    @Override
    @Transactional
    public Order adjustOrderB() {
        // 查询id=1的订单
        Order order = orderRepository.findById(1L)
                .orElseThrow(() -> new RuntimeException("订单不存在"));

        // 金额-200
        order.setAmount(order.getAmount().subtract(BigDecimal.valueOf(200)));

        // 更新时间
        order.setTradeTime(LocalDateTime.now());
        // 保存
        return orderRepository.save(order);

    }
}